import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";
import store from "@/store";
Vue.use(VueRouter);

//编程式路由导航重复导航会报错,我们需要重写push和replace解决这个问题
//1. 保存旧的push方法
const oldPushMethod = VueRouter.prototype.push;
//2.  重写push
VueRouter.prototype.push = function (
  location,
  onComplate = () => {},
  onAbort = () => {}
) {
  //内部使用的还是以前的push方法,但是我们给添加了处理异常的回调函数
  return oldPushMethod.call(this, location, onComplate, onAbort);
};

//1. 保存旧的replace方法
const oldReplaceMethod = VueRouter.prototype.replace;
//2. 重写push
VueRouter.prototype.replace = function (
  location,
  onComplate = () => {},
  onAbort = () => {}
) {
  //内部使用的还是以前的push方法,但是我们给添加了处理异常的回调函数
  return oldReplaceMethod.call(this, location, onComplate, onAbort);
};

const router = new VueRouter({
  routes,
  mode: "history",
});

const whitePath =[
  "login",
  "home",
  "register",
  "search",
  "detail",
  "addCartSuccess",
  "shopCart",
];
//token检验
router.beforeEach(async (to,from,next)=>{
  const token = store.state.user.token;
  //进行判断，判断token是否存在
  if(token){
    //存在，判断去的是不是登录页面，是则直接去home
    if(to.name === "login"){
      next("/home");
    }else{
      //判断是否有用户信息携带
      const isUserInfo = !!store.state.user.userInfo.nickName
      if(isUserInfo){
        next();
      }else{
        //没有用户信息，则直接获取用户信息
        try{
          await store.dispatch("user/getUserInfo");
          //获取用户信息成功next
          next();
        }catch(e){
          //获取用户信息失败，则去重新登录
          store.dispatch("user/getResetUser");
          next(`/login?redirect=${to.name}`)
        } 
      }
    }
  }else{
    //token不存在
    //判断去的地方是否是白名单
    if(whitePath.includes(to.name)){
      next();
    }else{
      //再次登录
      next(`/login?redirect=${to.name}`);
    }
  }
});

export default router;
